import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime
import os


class FlaskLogger:
    """统一的日志配置中心"""

    @staticmethod
    def _get_formatter(name_width=20):
        """统一的日志格式"""
        return logging.Formatter(
            f'%(asctime)s | %(name)-{name_width}s | %(levelname)-8s | %(filename)s:%(lineno)d | %(message)s'
        )

    @staticmethod
    def _get_file_handler(log_path, level=logging.DEBUG):
        """文件处理器工厂"""
        handler = RotatingFileHandler(
            filename=log_path,
            maxBytes=10 * 1024 * 1024,  # 10MB
            backupCount=5,
            encoding='utf-8'
        )
        handler.setLevel(level)
        handler.setFormatter(FlaskLogger._get_formatter())
        return handler

    @staticmethod
    def _get_console_handler(level=logging.INFO):
        """控制台处理器工厂"""
        handler = logging.StreamHandler()
        handler.setLevel(level)
        handler.setFormatter(FlaskLogger._get_formatter(15))  # 控制台名字显示宽度缩短
        return handler

    @classmethod
    def configure_app_logger(cls, app, base_log_dir="logs"):
        """配置Flask应用日志"""
        # 按日期创建目录
        date_dir = datetime.now().strftime('%Y-%m-%d')
        log_dir = os.path.join(app.root_path, base_log_dir, date_dir)
        os.makedirs(log_dir, exist_ok=True)

        log_file = os.path.join(log_dir, "flask.log")

        # 清除现有处理器
        app.logger.handlers.clear()

        # 添加处理器
        app.logger.addHandler(cls._get_file_handler(log_file))
        app.logger.addHandler(cls._get_console_handler())
        app.logger.setLevel(logging.DEBUG)

        # 禁用Werkzeug日志
        logging.getLogger('werkzeug').disabled = True
        return app.logger

    @classmethod
    def get_module_logger(cls, name, base_log_dir="logs"):
        """获取模块级Logger"""
        logger = logging.getLogger(name)

        if not logger.handlers:  # 避免重复添加
            # 按日期创建目录
            date_dir = datetime.now().strftime('%Y-%m-%d')
            log_dir = os.path.join(base_log_dir, date_dir)
            os.makedirs(log_dir, exist_ok=True)

            log_file = os.path.join(log_dir, "module.log")

            logger.setLevel(logging.DEBUG)
            logger.addHandler(cls._get_file_handler(log_file))
            logger.addHandler(cls._get_console_handler())

        return logger